import os
import sys
from string import Template
from pkg_tools import cmd, logger, cmd_with_result, write_file, make_dir_p, join_path, url_retrieve, create_tar_gz, \
    remove_file_or_dir, copy_file, release_package_remove_src
from conf_common import project_name, module_name, build_number, custom_install_cmd, custom_private_cmd, \
    install_conf_path, private_conf_path
from conf_backend import prod_yml_path, in_globe_start_param_name

base_path = f'{project_name}-{module_name}-install'
pwd = os.getcwd()


def build_all_back_end():
    cmd("rm -rf  ~/.m2/repository/com/xw/")
    cmd("mvn clean package -U -D maven.test.skip=true")
    make_dir_p(join_path(base_path, "bin"))
    copy_file(join_path('starter-admin', 'target', 'starter-admin.jar'),
              join_path(base_path, "bin", f'{module_name}.jar'))


def create_xwguard_install_conf():
    if install_conf_path is None or len(install_conf_path) == 0:
        logger.info(
            "not config install.conf relative path,will use 'custom_install_cmd' generate a common install.conf")
        conf = Template('''
[install]

cd $${workdir}
cp -rf bin conf version.txt log $${installdir}
mkdir -p /opt/webdata/file
# 自定义脚本
${custom_install_cmd}
[uninstall]
#用于配置卸载时模块的特殊处理
        ''')
        conf_content = conf.substitute({'custom_install_cmd': custom_install_cmd})
        write_file(join_path(pwd, base_path, 'install.conf'), conf_content)
    else:
        copy_file(install_conf_path, join_path(pwd, base_path, 'install.conf'))


def create_xwguard_private_conf():
    if private_conf_path is None or len(private_conf_path) == 0:
        logger.info(
            "not config private.conf relative path,will use 'custom_private_cmd' generate a common private.conf")
        write_file(join_path(pwd, base_path, 'private.conf'), custom_private_cmd)
    else:
        copy_file(private_conf_path, join_path(pwd, base_path, 'private.conf'))


def create_xwguard_start_sh():
    conf = Template('''
#!/bin/bash

#----------------------------------------------------
# 修改以下内容以适应本模块

# 安装目录
installdir=/usr/local/${module_name}

# 启动的入口jar包
mainjar=$${installdir}/bin/${module_name}.jar

# 启动参数，一般为配置文件，可以有多个
yml_path="-Dspring.config.location=$${installdir}/conf/application.yml"



#-----------------------------------------------------
# 以下内容一般不需要修改

# 加载全局配置
if [ -f /home/globe.conf ]; then source /home/globe.conf; fi;

# 内存设置
memset=$$(grep MemTotal /proc/meminfo | awk '{print $$2}')
# 设置为物理内存的1/16，这里可以根据需要酌情调整内存限制。
memset=$$(expr $$memset / 16000)
memset="-Xmx$${memset}m"

# 如果为研发环境，默认配置的内存大小，后台模块建议为256M，界面模块建议为1024M
if [ "x$${XW_DEVELOPMENT_ENV}" == "x1" ]; then
  memset="-Xmx512M"
fi

# 启动进程，如果已经启动，则退出

cd $${installdir}

pinfo=$$(ps -ef|grep "$${mainjar}"|grep -v grep)
if [ "x$${pinfo}" == "x" ]; then
  if [ -n "$${${in_globe_start_param_name}}" ]; then
    nohup java -jar  $${yml_path} $${${in_globe_start_param_name}} $${mainjar} > /dev/null 2>&1 &
  else
    nohup java -jar  $${yml_path} $${memset} $${mainjar} > /dev/null 2>&1 &
  fi
else 
  echo "$${mainjar} already running. exit."
  exit 0
fi
    ''')
    _in_globe_start_param_name = in_globe_start_param_name if in_globe_start_param_name \
                                                              is not None and len(in_globe_start_param_name) != 0 \
        else 'GLOBE_START_PARAM'
    conf_content = conf.substitute({'module_name': module_name,
                                    'in_globe_start_param_name': _in_globe_start_param_name
                                    })
    make_dir_p(join_path(pwd, base_path, 'bin'))
    write_file(join_path(pwd, base_path, 'bin', 'start.sh'), conf_content)


def create_xwguard_bin():
    conf = Template('''rundir=/usr/local/${module_name}/bin
runcmd=./start.sh
match=/usr/local/${module_name}/bin/${module_name}.jar''')
    conf_content = conf.substitute({'module_name': module_name})
    write_file(join_path(pwd, base_path, f'{module_name}.guard'), conf_content)


def create_xwguard_xagent():
    write_file(join_path(pwd, base_path, f'{module_name}.xagent'), '')


def create_xwguard_env_file():
    create_xwguard_install_conf()
    create_xwguard_private_conf()
    create_xwguard_start_sh()
    create_xwguard_bin()
    create_xwguard_xagent()


def create_project_conf():
    if prod_yml_path is not None and len(prod_yml_path) != 0:
        make_dir_p(join_path(base_path, "conf"))
        copy_file(prod_yml_path, join_path(base_path, "conf", 'application.yml'))


def release_package():
    write_file(join_path(base_path, 'version.txt'), build_number)
    release_package_remove_src(base_path, f'{base_path}-{build_number}.tar.gz')


def create_log_dir():
    make_dir_p(join_path(pwd, base_path, 'log'))
    write_file(join_path(pwd, base_path, 'log', '.empty-keep'), '')


if __name__ == '__main__':
    try:
        make_dir_p(base_path)
        build_all_back_end()
        create_xwguard_env_file()
        create_project_conf()
        create_log_dir()
        release_package()
    except Exception as err:
        logger.error('main exception:' + str(err))
        sys.stderr.write('main exception:' + str(err))
        sys.exit(1)
